package com.company.netty2;


import com.company.serialization.MsgpackDecoder;
import com.company.serialization.MsgpackEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 *
 */
public class EchoClient2 {

    public static void main(String[] args) {
        final String host = "localhost";
        final Integer port = 8080;

        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                int number = 5;
                //ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                //socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
                //socketChannel.pipeline().addLast(new StringDecoder());
                socketChannel.pipeline().addLast("msgpack decoder", new MsgpackDecoder());
                socketChannel.pipeline().addLast("msgpack encoder", new MsgpackEncoder());

                socketChannel.pipeline().addLast(new EchoClientHandlerWithEncoderAndDecoder(number));


            }
        });

        try {
            Channel channel = b.connect(host, port).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
